package com.happy_hao.msg.service.impl;

import com.happy_hao.msg.dto.EmailRequest;
import com.happy_hao.msg.dto.NoPeriodStartRequest;
import com.happy_hao.msg.dto.PeriodicSendRequest;
import com.happy_hao.msg.dto.SystemInfoRequest;
import com.happy_hao.msg.mapper.EmailMapper;
import com.happy_hao.msg.po.Email;
import com.happy_hao.msg.po.Sender;
import com.happy_hao.msg.service.EmailService;
import com.happy_hao.msg.task.EmailTask;
import com.happy_hao.msg.util.EmailUtil;
import com.happy_hao.msg.util.SnowFlakeUtil;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.*;
@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private EmailTask task;

    @Resource
    private EmailMapper emailMapper;

    @Resource
    private EmailUtil emailUtil;

    @Async
    @Override
    public void instantSend(@Valid EmailRequest emailRequest) throws MessagingException, UnsupportedEncodingException {
        emailUtil.send(emailRequest);
    }

    @Async
    @Override
    public void newScheduledSend(EmailRequest emailRequest) {
        emailUtil.newScheduledSend(emailRequest);
    }


    private final Map<String, ScheduledFuture<?>> tasks = new ConcurrentHashMap<>();

    public String periodicSend(PeriodicSendRequest periodicSendRequest) {
        String taskId = UUID.randomUUID().toString();
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        // 构建完整的URL
        String url = "http://1.95.204.186:8080/topbiz/msg/email/stopPeriodicSend/" + taskId;
//        String url = "http://127.0.0.1:8080/msg/email/stop/" + taskId;
        // 方法1：直接构建HTML内容
        String htmlContent = "<html><body>"
                + "<p>" + periodicSendRequest.getContent() + "</p>"
                + "<p>收到请点击以下链接：</p>"
                + "<p><a href=\"" + url + "\">" + url + "</a></p>"
                + "<p>或者复制链接到浏览器打开：<br>" + url + "</p>"
                + "</body></html>";
        periodicSendRequest.setContent(htmlContent);
        ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
            try {
                emailUtil.periodicSend(periodicSendRequest);
//                MimeMessage mimeMessage = javaMailSender.createMimeMessage();//创建一个邮件消息
//                MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true);
//                message.setFrom(from,"msg项目");
//                message.setTo(periodicSendRequest.getToEmail());
//                message.setSubject(periodicSendRequest.getSubject());
//                message.setText(htmlContent,true);
//                javaMailSender.send(mimeMessage);
            }catch (Exception e){
                e.printStackTrace();
            }
        }, 0, getPeriodFromCron(periodicSendRequest.getCron()), TimeUnit.SECONDS);

        tasks.put(taskId, future);
        return taskId;
    }

    //取消周期性任务
    public void stopPeriodicSend(String taskId) {
        ScheduledFuture<?> future = tasks.get(taskId);
        if (future != null) {
            future.cancel(true);
            tasks.remove(taskId);
        }
    }

    private static final long PT15S = 15;
    private static final long PT5M = 5*60;
    private static final long PT1H = 60*60;
    private static final long PT168H = 24*7*60*60;
    private static final long PT24H = 24*60*60;
//    PT5M = 每5分钟 PT1H = 每小时
//    PT24H = 每天 PT168H = 每周
    private long getPeriodFromCron(String cron) {
        // 简化的cron解析逻辑（实际项目建议使用CronSequenceGenerator）
        if(cron.equalsIgnoreCase("PT5M")){
            return PT5M;
        } else if (cron.equalsIgnoreCase("PT1H")) {
            return PT1H;
        }else if(cron.equalsIgnoreCase("PT24H")){
            return PT24H;
        }else if(cron.equalsIgnoreCase("PT168H")){
            return PT168H;
        }else if(cron.equalsIgnoreCase("PT15S")){
            return PT15S;
        }
        return PT15S;
    }


    //周期性发送
    private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
    private final Map<String, EmailTask> tasks2 = new ConcurrentHashMap<>();

        public String startEmailTask(NoPeriodStartRequest request) {
        // 创建间隔队列：30天、7天、6天、5天、4天、3天、2天、1天（转换为毫秒）
        Queue<Long> intervals = new LinkedList<>();
//        intervals.add(TimeUnit.DAYS.toMillis(30));
//        intervals.add(TimeUnit.DAYS.toMillis(21));
//        intervals.add(TimeUnit.DAYS.toMillis(14));
//        intervals.add(TimeUnit.DAYS.toMillis(7));
//        intervals.add(TimeUnit.DAYS.toMillis(6));
//        intervals.add(TimeUnit.DAYS.toMillis(5));
//        intervals.add(TimeUnit.DAYS.toMillis(4));
//        intervals.add(TimeUnit.DAYS.toMillis(3));
//        intervals.add(TimeUnit.DAYS.toMillis(2));
//        intervals.add(TimeUnit.DAYS.toMillis(1));
        //增加一个5s的
            System.out.println("开始执行定时任务"+request.getTimes());
        List<Integer> times = request.getTimes();
        // 添加时间间隔
            for (Integer time : times) {
                //把Integer转换成int
                int timeInt = time;
                intervals.add(TimeUnit.SECONDS.toMillis(timeInt));
            }
//        intervals.add(TimeUnit.SECONDS.toMillis(15));
//        intervals.add(TimeUnit.SECONDS.toMillis(5));

        String taskId = UUID.randomUUID().toString();
//        String url = "http://127.0.0.1:8080/msg/email/noPeriodsTop/" + taskId;
        String url = "http://1.95.204.186:8080/topbiz/msg/email/noPeriodsTop/" + taskId;
        // 方法1：直接构建HTML内容
        String htmlContent = "<html><body>"
                + "<p>" + request.getContent() + "</p>"
                + "<p>收到请点击以下链接：</p>"
                + "<p><a href=\"" + url + "\">" + url + "</a></p>"
                + "<p>或者复制链接到浏览器打开：<br>" + url + "</p>"
                + "</body></html>";
        request.setContent(htmlContent);
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
//        EmailTask task = new EmailTask(taskId,request.getFromEmail(), request.getToEmail(), request.getSubject(),
//        htmlContent,  intervals, executor, javaMailSender);
            task.setTaskId(taskId);
            task.setFromEmail(request.getFromEmail());
            task.setToEmail(request.getToEmail());
            task.setSubject(request.getSubject());
            task.setContent(htmlContent);
            task.setIntervals(intervals);
            task.setExecutor(executor);
        tasks2.put(taskId, task);

        // 立即执行第一次发送
        executor.execute(task);

        return taskId;
    }

    //取消周期性发送
    public void cancelEmailTask(String taskId) {
        EmailTask task = tasks2.remove(taskId);
        if (task != null) {
            task.cancel();
        }
    }

    @Override
    public void systemInfo(SystemInfoRequest systemInfoRequest) {
        emailUtil.sendSampleMail(systemInfoRequest.getTo(), systemInfoRequest.getSubject(), systemInfoRequest.getContext());
    }


}
